<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="{ type: 'checkbox' }">
      <template #headerTop>
        <TableSelect :selectRows="getSelectRows()" @clear="clearSelectedRowKeys()" />
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleGenCode" :disabled="getSelectRows().length < 1">
          <Icon icon="ant-design:download-outlined"></Icon>
          生成
        </a-button>
        <a-button type="primary" @click="openCreateModal(true)">
          <Icon icon="ant-design:appstore-add-outlined"></Icon>
          创建
        </a-button>
        <a-button type="primary" @click="openImportModal(true)">
          <Icon icon="ant-design:import-outlined"></Icon>
          导入
        </a-button>
        <a-button type="primary" @click="handleDelete(null, true)" :disabled="getSelectRows().length < 1">
          <Icon icon="ant-design:delete-outlined"></Icon>
          删除
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:code-outlined',
              label: '预览',
              onClick: handlePreview.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              label: '修改',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record, false),
              },
            },
            {
              icon: 'ant-design:download-outlined',
              label: '生成',
              onClick: handleGenCode.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <CreateModal @register="registerCreateModal" @success="reload()" />
    <ImportModal @register="registerImportModal" @success="reload()" />
    <PreviewModal @register="registerPreviewModal" />
    <download-modal @register="registerDownloadModal" @success="downloadCode" />
  </div>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import { useGo } from '/@/hooks/web/usePage';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { getBasicColumns, getFormConfig } from './config';
  import { useModal } from '/@/components/Modal';
  import { Loading, useLoading } from '/@/components/Loading';
  import { Icon } from '/@/components/Icon';
  import { PageEnum } from '/@/enums/pageEnum';
  import CreateModal from './modal/create/index.vue';
  import ImportModal from './modal/import/index.vue';
  import PreviewModal from './modal/preview/index.vue';
  import downloadModal from './modal/download/index.vue';
  import { downloadByData } from '/@/utils/file/download';
  import CRUD from '/@/crud/core/init';
  import TableSelect from '/@/components/Custom/TableSelect/index.vue';
  import * as _API from './api';

  export default defineComponent({
    name: 'Gen',
    components: {
      PreviewModal,
      downloadModal,
      Icon,
      Loading,
      BasicTable,
      CreateModal,
      ImportModal,
      TableAction,
      TableSelect,
    },
    setup() {
      const go = useGo();
      const crud = CRUD({ title: '代码生成器', crudMethod: { ..._API } });
      const [openFullLoading, closeFullLoading] = useLoading({ tip: '加载中...' });
      const [registerCreateModal, { openModal: openCreateModal }] = useModal(); // 创表 modal
      const [registerImportModal, { openModal: openImportModal }] = useModal(); // 导入
      const [registerPreviewModal, { openModal: openPreviewModal }] = useModal(); // 预览
      const [registerDownloadModal, { openModal: openDownloadModal, closeModal: closeDownloadModal }] = useModal(); // 下载
      const [registerTable, { reload, getSelectRowKeys, getSelectRows, clearSelectedRowKeys }] = useTable({
        api: _API.getAPI,
        columns: getBasicColumns(),
        formConfig: getFormConfig(),
        useSearchForm: true,
        showTableSetting: true,
        size: 'small',
        bordered: true,
        showIndexColumn: true,
        canResize: false,
        clickToRowSelect: false,
        rowKey: 'tableId',
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });
      function handlePreview(record: Recordable) {
        _API.getTplList().then((res: any) => {
          openPreviewModal(true, {
            tableId: record.tableId,
            tplList: res?.items,
          });
        });
      }

      function handleEdit(record: Recordable) {
        // 跳转编辑页面
        go(PageEnum.EDIT_TABLE + record.tableId);
      }

      /**
       * @vuese
       * @Description: 删除事件
       * @arg {*} record
       * @arg {*} useConfirm
       */
      async function handleDelete(record: Recordable, useConfirm: Boolean) {
        crud
          .toDel({
            params: {
              ids: (record && [record.tableId]) ?? getSelectRowKeys(),
            },
            useConfirm,
            refresh: false,
          })
          .then((res) => {
            reload();
          });
      }
      /**
       * @vuese
       * @Description:生成代码回调
       * @arg {*} ids
       * @arg {*} tpl
       */
      const downloadCode = async ({ ids, tpl }) => {
        closeDownloadModal();
        openFnFullLoading();
        const data = await _API.batchGenCode({ ids, tplList: tpl });
        await downloadByData(data, 'genCode.zip');
      };
      /**
       * @vuese
       * @Description:生成代码
       * @arg {*} record
       * @since: 2022-04-04
       */
      async function handleGenCode(record: Recordable) {
        openDownloadModal(true, { rows: (record?.tableId && [record?.tableId]) || getSelectRowKeys() });
      }
      function openFnFullLoading() {
        openFullLoading();
        setTimeout(() => {
          closeFullLoading();
        }, 2500);
      }

      return {
        registerTable,
        registerCreateModal,
        registerImportModal,
        registerPreviewModal,
        registerDownloadModal,
        openCreateModal,
        openImportModal,
        handlePreview,
        handleEdit,
        handleDelete,
        handleGenCode,
        reload,
        getSelectRows, // 获取选中
        clearSelectedRowKeys, // 清空选中
        openFnFullLoading,
        downloadCode,
      };
    },
  });
</script>
